package com.flycat.interceptor;

import com.alibaba.fastjson.JSON;
import com.flycat.common.enumeration.SysRoleEnum;
import com.flycat.common.util.ApplicationContextUtil;
import com.flycat.common.util.RoleUtils;
import com.flycat.common.util.SessionUtils;
import com.flycat.core.Result;
import com.flycat.core.ResultGenerator;
import com.flycat.dao.po.MerchantInfo;
import com.flycat.dao.po.SysPermission;
import com.flycat.service.SysPermissionRoleService;
import com.flycat.service.SysPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * @Author yalei.chen
 * @Date 2017/10/17
 * @Since JDK 1.8
 */
public class AccessInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result<String> dto = new Result<>();
        //从session中获取登录用户
        MerchantInfo user = (MerchantInfo)request.getSession().getAttribute(SessionUtils.STORE_SESSION_USER);
        //用户未登录则返回false
        if(user == null){
            dto = ResultGenerator.genFailResult("用户未登录");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().print(JSON.toJSONString(dto));
            return false;
        }
        //获取用户的访问路径
        String requestURI = request.getRequestURI();

        ApplicationContext applicationContext = ApplicationContextUtil.getApplicationContext();
        SysPermissionService sysPermissionService = applicationContext.getBean(SysPermissionService.class);

        List<SysPermission> permissions = sysPermissionService.findByRole(RoleUtils.merchantType2Role(user.getType()));

        if(permissions != null && permissions.size() > 0){
            //URI是否包含功能字段，默认为false
            boolean flag = false;
            for(SysPermission sysPermission : permissions){ //循环遍历该用户的功能列表，若包含功能则置为true并结束循环
                String url = sysPermission.getUrl();

                flag = hasAccess(requestURI, url);

                if(flag){
                    return flag;
                }
            }
        }

        dto = ResultGenerator.genFailResult("该用户没有操作权限，请联系系统管理员！");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().print(JSON.toJSONString(dto));
        return false;
    }


    /**
     * 判断requestURI是否匹配url
     * @param requestURI
     * @param url
     * @return
     */
    private boolean hasAccess(String requestURI,String url){

        if(url.endsWith("**")){

            url = url.substring(0,url.length()-2);

            if(!url.equals("/") && url.endsWith("/")){
                url = url.substring(0,url.length()-1);
            }

            if(StringUtils.isNotEmpty(url) && requestURI.contains(url)){
                return true;
            }
        }else {

            if(url.endsWith("*")){

                url = url.substring(0,url.length()-1);

                if("/".equals(url)){
                    return true;
                }

                String[] split = requestURI.split(url);

                if(split != null && split.length > 0){

                    if(split.length == 1){
                        return true;
                    }else if(split.length == 2 && !split[1].contains("/")){
                        return true;
                    }
                }

            }else {

                if(requestURI.endsWith(url)){
                    return true;
                }

            }


        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
